import sys
from pathlib import Path
import matplotlib.pyplot as plt
import data_preprocess
import visual
import console
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
import os


class MainForm(QMainWindow, visual.Ui_MainWindow):
    def __init__(self):
        super(MainForm, self).__init__()
        self.setupUi(self)
        self.data = ''
        self.filename = ''
        self.actionOpen.triggered.connect(self.dataset_fig)
        self.actionFigures.triggered.connect(self.result_fig)
        self.pushButton.clicked.connect(self.train)
        self.pushButton_2.clicked.connect(self.detect)
        self.pushButton_3.clicked.connect(self.select)

    def initial(self):
        """
        初始化参考序列图像
        :return:
        """
        self.data = 'ecg'
        self.filename = 'chfdb_chf01_275.pkl'
        self.generate_fig()
        self.filename = 'chfdb_chf13_45590.pkl'
        self.generate_fig()
        self.filename = 'chfdbchf15.pkl'
        self.generate_fig()
        self.data = 'respiration'
        self.filename = 'nprs44.pkl'
        self.generate_fig()
        self.data = 'space_shuttle'
        self.filename = 'TEK16.pkl'
        self.generate_fig()

    def generate_fig(self):
        """
        生成参考序列图像
        :return:
        """
        # 生成样本序列并新建路径
        all_dataset = data_preprocess.PreprocessData(self.data, self.filename, augment=False)
        feature_dim = all_dataset.trainData.size(-1)  # 输入特征的维数
        test_dataset = all_dataset.testData.contiguous().view(1, -1, all_dataset.testData.size(-1)).transpose(0, 1)
        targets = []  # 待检测样本序列
        for channel_idx in range(feature_dim):
            target = data_preprocess.restore(test_dataset.cpu()[:, 0, channel_idx],
                                             all_dataset.mean[channel_idx],
                                             all_dataset.std[channel_idx]).numpy()
            targets.append(target)
        fig_dir = Path('dataset', self.data, 'figures').with_suffix('')
        fig_dir.mkdir(parents=True, exist_ok=True)

        # 生成待检测样本序列
        fig, ax = plt.subplots(figsize=(15, 5))
        ax.set_xlabel('Index', fontsize=15)  # x轴
        ax.set_ylabel('Value', fontsize=15)  # y轴
        for i in range(feature_dim):
            ax.plot(targets[i], color='black', marker='.', linestyle='-', markersize=1, linewidth=0.5)
        plt.savefig(str(fig_dir.joinpath(self.filename[:-4]).with_suffix('.png')))
        plt.close()

    def output_Fig(self, filename):
        """
        显示选中图片
        :return:
        """
        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(300,300,300,120);font-size:10px;font-weight:bold;font-family:宋体;}"
                                 )
        img = QtGui.QPixmap(filename).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(img)

    def output_datasetFig(self):
        """
        检测前展示待检测样本序列
        :return:
        """
        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(300,300,300,120);font-size:10px;font-weight:bold;font-family:宋体;}"
                                 )
        path = str(Path('dataset', self.data, 'figures', self.filename).with_suffix('.png'))
        img = QtGui.QPixmap(path).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(img)

    def output_resultFig(self):
        """
        检测后展示检测结果
        :return:
        """
        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(300,300,300,120);font-size:10px;font-weight:bold;font-family:宋体;}"
                                 )
        # path = str(Path('result', self.data, self.filename, 'figures', 'anomalyFig_channel0.png'))
        path = str(Path('figures', self.data, self.filename, 'Result.png'))
        img = QtGui.QPixmap(path).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(img)

    def dataset_fig(self):
        """
        数据序列图片选择
        :return:
        """
        open_path = r'.\dataset'
        filename, filetype = QFileDialog.getOpenFileName(self, '选取文件', open_path, 'All Files(*);;Text Files(*.txt)')

        # 显示待检测图像
        self.output_Fig(filename)

    def result_fig(self):
        """
        检测结果图片选择
        :return:
        """
        open_path = r'.\result'
        filename, filetype = QFileDialog.getOpenFileName(self, '选取图像', open_path, 'All Files(*);;Text Files(*.txt)')

        # 显示检测结果
        self.output_Fig(filename)

    def train(self):
        """
        执行训练脚本
        :return:
        """
        os.system('python training.py --data ' + self.data + ' --filename ' + self.filename)

    def detect(self):
        """
        执行异常检测脚本
        :return:
        """
        os.system('python detection.py --data ' + self.data + ' --filename ' + self.filename)

        # 显示检测结果
        self.output_resultFig()

    def select(self):
        """
        显示通过下拉栏选择的数据序列
        :return:
        """
        self.data = self.comboBox.currentText()
        self.filename = self.comboBox_2.currentText()

        # 显示待检测序列图片
        self.output_datasetFig()


class SecondForm(QMainWindow, console.Ui_MainWindow):
    def __init__(self):
        super(SecondForm, self).__init__()
        self.setupUi(self)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainForm()
    win.show()
    win.initial()
    sys.exit(app.exec_())
